﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HANS_WeChat.Base.Model.DbModel;
using HANS_WeChat.Base.Model.WeModel;
using HANS_WeChat.Base.DAL;
using HANS.Utility.Extensions;
using HANS.DataBaseTool;
using HANS_WeChat.Base.Model.WeModel.CommonMenu;
using HANS.WeChat;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Menu;
using Senparc.Weixin.Entities;

namespace HANS_WeChat.Base.Model.DbModel
{
    /// <summary>
    /// 微信菜单
    /// </summary>
    public class WeChatMenuService
    {
        private static HANSWeChatDataEntityDAL<Commonmenu> CommonMenuDal = new HANSWeChatDataEntityDAL<Commonmenu>();//微信普通菜单


        /// <summary>
        /// loadCommonMenu
        /// </summary>
        /// <param Menuname="id"></param>
        /// <returns></returns>
        public static Commonmenu LoadCommonmenu(string id)
        {
            return CommonMenuDal.Load(id);
        }
        /// <summary>
        /// 新增CommonMenu
        /// </summary>
        /// <param Menuname="commonmenu"></param>
        /// <returns></returns>
        public static Msg InsertCommonMenu(Commonmenu commonmenu)
        {
            Msg msg = new Msg();
            if (CommonMenuDal.Insert(commonmenu) > 0)
            {
                msg.AddMsg("添加成功！");
            }
            else
            {
                msg.Result = false;
                msg.AddMsg("添加失败！");
            }

            return msg;
        }
        /// <summary>
        /// 删除CommonMenu 子菜单会删除
        /// </summary>
        /// <param Menuname="id"></param>
        /// <returns></returns>
        public static Msg DeleteCommonMenu(string id)
        {
            Msg msg = new Msg();
            var ChildrenList = CommonMenuDal.List(new Commonmenu() { Parent_id = id }, "", "Menuorder");
            if (ChildrenList.Count > 0)
            {
                foreach (var item in ChildrenList)
                {
                    try
                    {
                        CommonMenuDal.Delete(item.Id);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                }
                if (CommonMenuDal.Delete(id) > 0)
                {
                    msg.AddMsg("删除成功！子菜单删除成功！");
                }
                else
                {
                    msg.Result = false;
                    msg.AddMsg("删除失败！请查看子菜单删除情况！");
                }

            }
            else
            {
                if (CommonMenuDal.Delete(id) > 0)
                {
                    msg.AddMsg("删除成功！");
                }
                else
                {
                    msg.Result = false;
                    msg.AddMsg("删除失败！");
                }
            }

            return msg;
        }
        /// <summary>
        /// 修改 CommonMenu
        /// </summary>
        /// <param Menuname="commonmenu"></param>
        /// <returns></returns>
        public static Msg UpdateCommonMenu(Commonmenu commonmenu)
        {
            Msg msg = new Msg();
            if (CommonMenuDal.Update(commonmenu) > 0)
            {
                msg.AddMsg("修改成功！");
            }
            else
            {
                msg.Result = false;
                msg.AddMsg("修改失败！");
            }
            return msg;
        }
        /// <summary>
        /// 获取数据库中的微信菜单
        /// </summary>
        /// <param Menuname="wechat">微信号（如果管理多个微信公众号的情况下填写）</param>
        /// <returns></returns>
        public static List<WeChatCommonMunu> GetCommonMenuList(string wechat = "")
        {
            List<WeChatCommonMunu> WeChatCommonMunuList = new List<WeChatCommonMunu>();
            string _where = "and  Parent_id=''";
            if (wechat.IsNotNullAndNotWhiteSpace())
            {
                _where += string.Format(" and  Wechat='{0}'", wechat);

            }
            else
            {
                _where += " and  Wechat <>''";
            }
            var parentList = CommonMenuDal.List(new Commonmenu() { }, _where, "Menuorder");
            foreach (var item in parentList)//因为微信菜单 主只有3 次最多5 所以不采用递归去做
            {
                WeChatCommonMunu _weChatCommonMunu = new WeChatCommonMunu();
                CommonMunu2WeChatCommonMunu(item, ref _weChatCommonMunu);
                var ChildrenList = CommonMenuDal.List(new Commonmenu() { Parent_id = item.Id }, "", "Menuorder");
                foreach (var ChildItem in ChildrenList)
                {
                    WeChatCommonMunu _ChildweChatCommonMunu = new WeChatCommonMunu();
                    CommonMunu2WeChatCommonMunu(ChildItem, ref _ChildweChatCommonMunu);
                    _ChildweChatCommonMunu.ParentName = item.Menuname;
                    _weChatCommonMunu.WeChatCommonMunuChild.Add(_ChildweChatCommonMunu);
                }
                WeChatCommonMunuList.Add(_weChatCommonMunu);
            }

            return WeChatCommonMunuList;
        }
        /// <summary>
        /// 获取Db父菜单
        /// </summary>
        /// <param Menuname="wechat">微信号（如果管理多个微信公众号的情况下填写）</param>
        /// <returns></returns>
        public static List<Commonmenu> GetCommonMainMenuList(string wechat = "")
        {

            List<Commonmenu> CommonMenuList = new List<Commonmenu>();
            string _where = "and  Parent_id=''";
            if (wechat.IsNotNullAndNotWhiteSpace())
            {
                _where += string.Format(" and  Wechat='{0}'", wechat);
            }
            else
            {
                _where += " and  Wechat <> ''";

            }
            CommonMenuList = CommonMenuDal.List(new Commonmenu() { }, _where, "Menuorder");//

            return CommonMenuList;
        }
        /// <summary>
        /// CommonMunu2WeChatCommonMunu
        /// </summary>
        /// <param Menuname="_Commonmenu"></param>
        /// <param Menuname="_WeChatCommonMunu"></param>
        private static void CommonMunu2WeChatCommonMunu(Commonmenu _Commonmenu, ref WeChatCommonMunu _WeChatCommonMunu)
        {
            _WeChatCommonMunu.Id = _Commonmenu.Id;
            _WeChatCommonMunu.Parent_id = _Commonmenu.Parent_id;
            _WeChatCommonMunu.Wechat = _Commonmenu.Wechat;
            _WeChatCommonMunu.Menuname = _Commonmenu.Menuname;
            _WeChatCommonMunu.Menukey = _Commonmenu.Menukey;
            _WeChatCommonMunu.Menutype = _Commonmenu.Menutype;
            _WeChatCommonMunu.Url = _Commonmenu.Url;
            _WeChatCommonMunu.Media_id = _Commonmenu.Media_id;
            _WeChatCommonMunu.Appid = _Commonmenu.Appid;
            _WeChatCommonMunu.Pagepath = _Commonmenu.Pagepath;
            _WeChatCommonMunu.Menuorder = _Commonmenu.Menuorder;
        }

        //TODO:微信菜单同步到数据库
        public static Msg CommonMenuCloudDownload()
        {
            Msg msg = new Msg();
            // var Token = CommonApi.GetToken(WeChatBaseInfo.AppID, WeChatBaseInfo.AppSecret);
            GetMenuResult menuResult = CommonApi.GetMenu(WeChatBaseInfo.AppID);
            if (menuResult.errmsg.IsNull() && menuResult.errcode.ToString() == "请求成功" && menuResult.menu.button.Count() > 0)
            {
                int parentOder = 1;

                List<WeChatMenuButton> WeChatMenuButtonList = new List<WeChatMenuButton>();
                foreach (var item in (menuResult.menu as ButtonGroup).button)
                {
                    WeChatMenuButton weChatMenuButton = new WeChatMenuButton();
                    Dictionary<string, string> Paerntdictionary = item.GetDictionaryPropertyValues();//获取主菜单的属性及其属性值
                    Commonmenu _commonmenu = MenucloudDownload2Commonmenu(WeChatBaseInfo.AppID, parentOder, Paerntdictionary);
                    weChatMenuButton._Commonmenu = _commonmenu;//设置主菜单
                    if (item.GetType() == typeof(SubButton))//判断是不是二级菜单
                    {
                        int childOrder = 1;
                        foreach (var ChildItem in (item as SubButton).sub_button)//处理二级菜单
                        {
                            Dictionary<string, string> ChildDictionary = ChildItem.GetDictionaryPropertyValues();
                            Commonmenu _Childcommonmenu = MenucloudDownload2Commonmenu(WeChatBaseInfo.AppID, childOrder, ChildDictionary, weChatMenuButton._Commonmenu.Id);
                            weChatMenuButton._CommonmenuList.Add(_Childcommonmenu);
                            childOrder++;
                        }
                    }
                    WeChatMenuButtonList.Add(weChatMenuButton);
                    parentOder++;

                }
                msg = CommonMenuCloudDownloaded(WeChatMenuButtonList);
            }
            else
            {
                msg.Result = false;
                msg.AddMsg("微信服务器查不到菜单，请查看APPID配置是否正确！");
            }


            return msg;
        }

        /// <summary>
        /// 将微信服务器的菜单添加到数据库，但是之前的必须删掉
        /// </summary>
        /// <param name="weChatMenuButtonList"></param>
        /// <returns></returns>
        private static Msg CommonMenuCloudDownloaded(List<WeChatMenuButton> weChatMenuButtonList)
        {
            Msg msg = new Msg();
            string DeleteSql = @"DELETE FROM commonmenu";
            DbHelper.ExecuteSQLHelper(DeleteSql, HANS_Base.HANSDataBaseLink.wechat, msg);
            if (msg.Result)
            {
                try
                {
                    foreach (var item in weChatMenuButtonList)
                    {
                        CommonMenuDal.Insert(item._Commonmenu);
                        if (item._CommonmenuList.Count > 0)
                        {
                            foreach (var childitem in item._CommonmenuList)
                            {
                                CommonMenuDal.Insert(childitem);
                            }
                        }
                    }
                    msg.AddMsg("同步成功！");
                }
                catch (Exception)
                {

                    msg.Result = false;
                    msg.AddMsg("同步到数据中出错！");
                }

            }
            else
            {
                msg.Result = false;
                msg.AddMsg("数据删菜单删除失败，微信菜单无法同步到数据库！");
            }

            return msg;
        }

        //TODO:数据库同步到微信菜单

        /// <summary>
        /// 数据库同步到微信菜单
        /// </summary>
        /// <returns></returns>
        public static Msg CommonMenuCloudUpload()
        {
            Msg msg = new Msg();
            List<WeChatCommonMunu> WeChatMenuList = new List<WeChatCommonMunu>();
            //形成父子的list 然后遍历
            WeChatMenuList = GetCommonMenuList();
            ButtonGroup buttonGroup = new ButtonGroup();
            foreach (var item in WeChatMenuList)
            {

                var button = BecomeWeChatButtion(item);
                buttonGroup.button.Add(button);

            }
            WxJsonResult wxJsonResult=  CommonApi.CreateMenu(WeChatBaseInfo.AppID, buttonGroup);
            if (wxJsonResult.errcode==0)
            {
                msg.AddMsg("上传成功！请稍后查看，若没有刷新，请取消关注，然后再次关注即可！");
            }
            else
            {
                msg.Result = false;
                msg.AddMsg("上传失败！，原因：errcode=" + wxJsonResult.errcode + ";errmsg=\"" + wxJsonResult.errmsg + "\"");

            }
            return msg;
        }

        /// <summary>
        /// 数据库button转成微信菜单
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private static BaseButton BecomeWeChatButtion(WeChatCommonMunu item)
        {
            if (item.WeChatCommonMunuChild.Count > 0)//有主菜单。子菜单
            {
                SubButton subButton = new SubButton();
                subButton.name = item.Menuname;
                foreach (var _button in item.WeChatCommonMunuChild)
                {
                    subButton.sub_button.Add(ReflexClass(_button.Menutype, _button));
                }

                return subButton;
            }
            else//只有一个按钮
            {
                BaseButton baseButton = new BaseButton();
                baseButton = ReflexClass(item.Menutype, item);
                return baseButton;
            } 
        }
        /// <summary>
        /// 形成各类的Button
        /// </summary>
        /// <param name="Buttontype"></param>
        /// <param name="weChatCommonMunu"></param>
        /// <returns></returns>
        private static SingleButton ReflexClass(string Buttontype, WeChatCommonMunu weChatCommonMunu)
        {

            SingleButton _object = null;
            switch (Buttontype)
            {
                case "click":
                    _object = new SingleClickButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        key = weChatCommonMunu.Menukey,
                        type = WeChatMenuType.click.EnumDescription()
                    };
                    break;
                case "view":
                    _object = new SingleViewButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        type = WeChatMenuType.view.EnumDescription(),
                        url = weChatCommonMunu.Url
                    };
                    break;
                case "scancode_push":
                    _object = new SingleScancodePushButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        key = weChatCommonMunu.Menukey,
                        type = WeChatMenuType.scancode_push.EnumDescription()
                    };
                    break;
                case "scancode_waitmsg":
                    _object = new SingleScancodeWaitmsgButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        key = weChatCommonMunu.Menukey,
                        type = WeChatMenuType.scancode_waitmsg.EnumDescription()
                    };
                    break;
                case "pic_sysphoto":
                    _object = new SinglePicSysphotoButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        key = weChatCommonMunu.Menukey,
                        type = WeChatMenuType.pic_sysphoto.EnumDescription()
                    };
                    break;
                case "pic_photo_or_album":
                    _object = new SinglePicPhotoOrAlbumButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        key = weChatCommonMunu.Menukey,
                        type = WeChatMenuType.pic_photo_or_album.EnumDescription()
                    };
                    break;
                case "pic_weixin":
                    _object = new SinglePicWeixinButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        key = weChatCommonMunu.Menukey,
                        type = WeChatMenuType.pic_weixin.EnumDescription()
                    };
                    break;
                case "location_select":
                    _object = new SingleLocationSelectButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        key = weChatCommonMunu.Menukey,
                        type = WeChatMenuType.location_select.EnumDescription()
                    };
                    break;
                case "media_id":
                    _object = new SingleMediaIdButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        type = WeChatMenuType.media_id.EnumDescription(),
                        media_id = weChatCommonMunu.Media_id
                    };
                    break;
                case "view_limited":
                    _object = new SingleViewLimitedButton()
                    {
                        name = weChatCommonMunu.Menuname,
                        type = WeChatMenuType.view_limited.EnumDescription(),
                        media_id = weChatCommonMunu.Media_id
                    };
                    break;
                case "miniprogram":
                    _object = new SingleMiniProgramButton()
                    {
                        appid = weChatCommonMunu.Appid,
                        name = weChatCommonMunu.Menuname,
                        pagepath = weChatCommonMunu.Pagepath,
                        type = WeChatMenuType.miniprogram.EnumDescription(),
                        url = weChatCommonMunu.Url
                    };
                    break;
                default:
                    _object = null;
                    break;
            }

            return _object;
        }

        /// <summary>
        /// 微信菜单转换成数据库实体
        /// </summary>
        /// <param name="Wechat"></param>
        /// <param name="Name"></param>
        /// <param name="Key"></param>
        /// <param name="Type"></param>
        /// <param name="MenuOrder"></param>
        /// <param name="Url"></param>
        /// <param name="Parent_Id"></param>
        /// <param name="Appid"></param>
        /// <param name="Media_id"></param>
        /// <param name="Pagepath"></param>
        /// <returns></returns>
        private static Commonmenu MenucloudDownload2Commonmenu(string Wechat, string Name, string Key, string Type, Int32? MenuOrder, string Url = "", string Parent_Id = "", string Appid = "", string Media_id = "", string Pagepath = "")
        {

            string guid = "";
            return new Commonmenu()
            {
                Id = guid.NewGuid(),
                Wechat = Wechat,
                Menuname = Name,
                Menukey = Key,
                Menutype = Type,
                Menuorder = MenuOrder,
                Url = Url,
                Parent_id = Parent_Id,
                Appid = Appid,
                Media_id = Media_id,
                Pagepath = Pagepath

            };
        }

        /// <summary>
        /// 微信菜单转换成数据库实体
        /// </summary>
        /// <param name="Wechat"></param>
        /// <param name="MenuOrder"></param>
        /// <param name="dictionary"></param>
        /// <param name="Parent_Id"></param>
        /// <returns></returns>
        private static Commonmenu MenucloudDownload2Commonmenu(string Wechat, Int32? MenuOrder, Dictionary<string, string> dictionary, string Parent_Id = "")
        {

            string guid = "";
            return new Commonmenu()
            {
                Id = guid.NewGuid(),
                Wechat = Wechat,
                Menuname = dictionary.ContainsKey("name") ? dictionary["name"] : "",
                Menukey = dictionary.ContainsKey("key") ? dictionary["key"] : "",
                Menutype = dictionary.ContainsKey("type") ? dictionary["type"] : "",
                Menuorder = MenuOrder,
                Url = dictionary.ContainsKey("url") ? dictionary["url"] : "",
                Parent_id = Parent_Id,
                Appid = dictionary.ContainsKey("appid") ? dictionary["appid"] : "",
                Media_id = dictionary.ContainsKey("media_id") ? dictionary["media_id"] : "",
                Pagepath = dictionary.ContainsKey("pagepath") ? dictionary["pagepath"] : "",

            };
        }
    }
}
